package com.moon.game.command.guest.gift;

import java.util.HashMap;
import java.util.List;

import com.moon.game.command.BaseCmd;
import com.moon.game.command.RequestSession;
import com.moon.game.constants.ErrorCode;
import com.moon.game.exception.GException;
import com.moon.game.manager.GiftMG;
import com.moon.game.resource.model.Gift;
import com.moon.game.service.GiftService;
import com.moon.game.service.ItemService;
import com.moon.game.vos.ErrorMsg;
import com.moon.game.vos.GiftVo;
import com.moon.game.vos.PlayerVo;

/**
 * @description 打开礼包
 * @author Ranger 作者 E-mail:haozi000005@163.com
 * @version 创建时间：2012-8-7 下午2:17:06
 */
public class OpenGiftCmd extends BaseCmd{

	@Override
	protected void runOnce(RequestSession req) throws GException {
		switch (req.getStatus()) {
			case STATU_INIT:
				doInit(req);
				break;
			case STATU_CHECK:
				doCheckSelf(req);
				break;
			case STATU_RETURN:
				doResponse(req);
				break;
			default:
				break;
		}
	}

	@Override
	protected void doResponse(RequestSession req) throws GException {
		String[] ps = req.getClientRequest().getPs();
		if (ps == null) {
			doResponsePsError(req);
			return;
		}
		Integer giftId = Integer.parseInt(ps[0]);
		if (giftId == null) {
			doResponsePsError(req);
			return;
		}
		PlayerVo player = getPlayerVo(req);
		List<GiftVo> giftList = player.getGiftList();
		if (giftList == null) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_NO_GIFT, "你目前没有任何礼包！"));
			return;
		}
		
		Gift gift = GiftMG.instance.getGiftById(giftId);
		if (gift == null) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "找不到指定的礼包资源！"));
			return;
		}
		
		if (!GiftService.checkGift(player, giftId)) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_NO_THE_GIFT, "你没有要打开的礼包！"));
			return;
		}
		
		if (player.getLevel() < gift.getLevel()) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_LACK_LEVEL, "打开" + gift.getName() + "需要等级" + gift.getLevel() + "，你的等级不够，快去升级吧！"));
			return;
		}
		
		HashMap<Integer, Integer> items = GiftService.analysisGiftItem(giftId);
		if (items != null) {
			//检查能否打开
			int addRoom = 0;
			for (Integer num : items.values()) {
				addRoom += num;
			}
			boolean canAdd = ItemService.checkRoom(req.getSid(), req.getPlayerId(), addRoom);
			if (!canAdd) {
				doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_ROOM, "打开【"+ gift.getName() +"】需要行囊空间" + addRoom + "你的空间不足！"));
				return;
			}
		}
		
		int ret = GiftService.delGift(req.getSid(), req.getPlayerId(), giftId);
		if (ret == 0) {
			//扣除礼包成功
			GiftService.addGiftReward(player, giftId);
		}else {
			doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_GIFT_BASE, "打开礼包失败！"));
			return;
		}
		
		req.setVO("gift_id", giftId);
		response(req, req.getClientResponse());
	}

}
